package com.liu.concurrent.sync;

import java.util.Collections;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者
 * 方案二：使用JUC包
 * @author liubo
 */
public class ProducerConsumerByJUC {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();


    }

}

class Data2{
    private int number = 0;
    //step1 创建Lock对象
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {
        //step2 加锁
        lock.lock();
        try {
            //STEP1 循环等待
            while (number!=0) {
                condition.await();
            }

            //STEP2 业务
            number++;
            System.out.println(Thread.currentThread().getName()+number);

            //STEP3 通知
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //step3 解锁
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        //step2 加锁
        lock.lock();
        try {
            //STEP1 循环等待
            while (number==0) {
                condition.await();
            }

            //STEP2 业务
            number--;
            System.out.println(Thread.currentThread().getName()+number);

            //STEP3 通知
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //step3 解锁
            lock.unlock();
        }
    }
}
